//
//  WBRefreshControl.swift
//  3月5的项目
//
//  Created by 哦哦 on 16/3/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

import SnapKit

private let RefreshHeight: CGFloat = 60

enum WBRefreshStatus: Int {
    //定义枚举项
    case Normal = 0         //默认状态
    case Pulling = 1        //下拉到临界值 等待刷新状态
    case Refreshing = 2     //正在刷新状态
}


class WBRefreshControl: UIControl {
    
    var statue: WBRefreshStatus = .Normal {
        didSet {
            //匹配枚举项
            switch statue {
            case .Normal:
                print("下拉刷新")
                tipLabel.text = "下拉刷新"
                indicationView.stopAnimating()
                arrowIcon.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                    if oldValue == .Refreshing {
                        //修改contentInset.top
                        var inset = self.scrollView!.contentInset
                        inset.top -= RefreshHeight
                        self.scrollView?.contentInset = inset
                    }
                })

            case .Pulling:
                print("松手刷新")
                tipLabel.text = "松手刷新"
                //旋转箭头  系统动画时间 是  0.25
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在刷新")
                tipLabel.text = "正在刷新"
                //隐藏箭头
                arrowIcon.hidden = true
                //转动小菊花
                indicationView.startAnimating()
                //做网络请求 刷新数据  俯视图的loadData
                self.sendActionsForControlEvents(.ValueChanged)
                
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //修改contentInset.top
                    var inset = self.scrollView!.contentInset
                    inset.top += RefreshHeight
                    self.scrollView?.contentInset = inset
                    
                })
            }
        }
    }
    func endRefreshing() {
        //延迟执行
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(USEC_PER_SEC) * 0.3))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
        
    }

    
    //刷新控件给定默认值 直接在构造方法内部指定大小
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshHeight, width: ScreenWidth, height: RefreshHeight)
        super.init(frame: rect)
        //设置背景颜色
//        self.backgroundColor = UIColor.blueColor()
        
        //设置界面
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //实现KVO观察的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        print("======================")
//        print(change)
        print(scrollView?.contentOffset)
        print(scrollView?.contentInset)
        print(print(scrollView?.contentSize))
        //1.实时获取 滚动视图垂直方向的位移
        let offsetY = scrollView?.contentOffset.y ?? 0
        //2.获取临界值   -124
         let condationValue = -(RefreshHeight + (scrollView?.contentInset.top ?? 0))
        if scrollView!.dragging {
            //用户正在拖拽的状态
            
//            if offsetY > -124 {
            if statue == .Pulling && offsetY > condationValue  {

                //下拉刷新的普通提示状态
//                print("下拉刷新")
//            } else {
                //垂直方向位置 达到临界值  变成 等待用户松手刷新状态
//                print("松手刷新")
                statue = .Normal
            } else if statue == .Normal && offsetY < condationValue {
                //垂直方向位置 达到临界值  变成 等待用户松手刷新状态
                statue = .Pulling

            }
            
            
        } else {
            //用户松手状态 && 并且是等待刷新状态 就修改为 刷新状态
//            print("正在刷新")
            
            //用户松手状态 && 并且是等待刷新状态 就修改为 刷新状态
            if statue == .Pulling {
                statue = .Refreshing
            }

        }
        
        
        
        //3.水平方向的位移  和 临界值比较  修改三种状态
    }
    
    
    //将要被添加到新的父视图上 会被调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //判断 newSuperview 是否是scrollView 或者是scrollView子视图
        
        //调用super
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
            //需要判断下拉刷新控件的父视图是否是 UIScrollView 及其子类
            //这个控件 可以提供 scrollView tableView collectionView 来进行下拉刷新使用
            //将父视图记录下来
            //            printLog("是scrollView")
            scrollView = myFather
            //观察父视图的contentOffset 这个属性
            //实时观察对象的属性的变化
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }

    
    private func setupUI() {
                addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
                backImageView.snp_makeConstraints { (make) -> Void in
                    make.left.right.bottom.equalTo(self)
                }
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
    }
    
     private var scrollView: UIScrollView?
    
    //MARK: 懒加载子视图
    private lazy var tipLabel: UILabel = UIFactory.labelFactory("下拉刷新", textColor: UIColor.darkGrayColor(), fontSize: 14)
    
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //小菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
    
    /**
     *  移除监听
     */
    
    deinit {
        //使用scrollView来移除监听
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}